package com.afollestad.materialdialogs;

import com.afollestad.materialdialogs.internal.MDAdapter;
import com.afollestad.materialdialogs.internal.MDButton;
import com.afollestad.materialdialogs.internal.MDRootLayout;
import com.afollestad.materialdialogs.utils.Const;
import com.afollestad.materialdialogs.utils.ResUtil;
import com.afollestad.materialdialogs.utils.UiUtil;
import ohos.agp.colors.RgbColor;
import ohos.agp.components.*;
import ohos.agp.components.element.ShapeElement;
import ohos.agp.render.Paint;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.utils.Point;
import ohos.agp.window.service.Display;
import ohos.agp.window.service.DisplayManager;
import ohos.agp.window.service.WindowManager;
import ohos.app.Context;
import ohos.global.configuration.Configuration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Optional;

/**
 * Used by MaterialDialog while initializing the dialog. Offloads some of the code to make the main
 * class cleaner and easier to read/maintain.
 *
 * @author Aidan Follestad (afollestad)
 */
class DialogInit {
    static int getInflateLayout(MaterialDialog.Builder builder) {
        if (builder.customView != null) {
            return ResourceTable.Layout_md_dialog_custom;
        } else if (builder.items != null || builder.baseItemProvider != null) {
            if (builder.checkBoxPrompt != null) {
                return ResourceTable.Layout_md_dialog_list_check;
            }
            return ResourceTable.Layout_md_dialog_list;
        } else if (builder.progress > -2) {
            return ResourceTable.Layout_md_dialog_progress;
        } else if (builder.indeterminateProgress) {
            if (builder.indeterminateIsHorizontalProgress) {
                return ResourceTable.Layout_md_dialog_progress_indeterminate_horizontal;
            }
            return ResourceTable.Layout_md_dialog_progress_indeterminate;
        } else if (builder.inputCallback != null) {
            if (builder.checkBoxPrompt != null) {
                return ResourceTable.Layout_md_dialog_input_check;
            }
            return ResourceTable.Layout_md_dialog_input;
        } else if (builder.checkBoxPrompt != null) {
            return ResourceTable.Layout_md_dialog_basic_check;
        }
        return ResourceTable.Layout_md_dialog_basic;
    }

    static void init(final MaterialDialog dialog) {
        final MaterialDialog.Builder builder = dialog.builder;
        int orientation = builder.getContext().getResourceManager().getConfiguration().direction;
        if ((orientation == Configuration.DIRECTION_HORIZONTAL) && (dialog != null)) {
            dialog.setSize(1200, 550);
        }
        // Set cancelable flag and dialog background color
        dialog.setAutoClosable(builder.canceledOnTouchOutside);
        if (builder.backgroundColor == 0) {
            builder.backgroundColor = ResUtil.getColor(dialog.getBuilder().getContext(), ResourceTable.Color_md_background_color);
        }
        if (builder.backgroundColor != 0) {
            ShapeElement drawable = new ShapeElement();
            drawable.setCornerRadius(ResUtil.getDimen(builder.getContext(),
                    ResourceTable.Float_md_bg_corner_radius));
            drawable.setRgbColor(new RgbColor(builder.backgroundColor));
        }

        // Retrieve default title/content colors.json
        if (!builder.titleColorSet) {
            builder.titleColor = ResUtil.getColor(builder.getContext(), ResourceTable.Color_textColorPrimary);
        }
        if (!builder.contentColorSet) {
            builder.contentColor = ResUtil.getColor(builder.getContext(), ResourceTable.Color_core_material_gray);
        }
        if (!builder.itemColorSet) {
            builder.itemColor = ResUtil.getColor(builder.getContext(), ResourceTable.Color_core_material_gray);
        }

        // Retrieve references to views
        dialog.title = UiUtil.getComponent(dialog.view, ResourceTable.Id_md_title);
        dialog.icon = UiUtil.getComponent(dialog.view, ResourceTable.Id_md_icon);
        dialog.titleFrame = UiUtil.getComponent(dialog.view, ResourceTable.Id_md_titleFrame);
        dialog.content = UiUtil.getComponent(dialog.view, ResourceTable.Id_md_content);
        dialog.listContainer = UiUtil.getComponent(dialog.view, ResourceTable.Id_md_listContainer);
        if ((orientation == Configuration.DIRECTION_HORIZONTAL) && (dialog != null) && (dialog.listContainer != null)) {
            dialog.listContainer.setHeight(550);
        }
        dialog.checkBoxPrompt = UiUtil.getComponent(dialog.view, ResourceTable.Id_md_promptCheckbox);

        dialog.buttonLayout = UiUtil.getComponent(dialog.view, ResourceTable.Id_buttonLayout);
        dialog.stackButtonLayout = UiUtil.getComponent(dialog.view, ResourceTable.Id_stackButtonLayout);
        // Button views initially used by checkIfStackingNeeded()
        dialog.positiveButton = UiUtil.getComponent(dialog.view, ResourceTable.Id_md_buttonDefaultPositive);
        dialog.stackPositiveButton = UiUtil.getComponent(dialog.view, ResourceTable.Id_md_stackButtonPositive);
        dialog.neutralButton = UiUtil.getComponent(dialog.view, ResourceTable.Id_md_buttonDefaultNeutral);
        dialog.negativeButton = UiUtil.getComponent(dialog.view, ResourceTable.Id_md_buttonDefaultNegative);
        dialog.stackNegativeButton = UiUtil.getComponent(dialog.view, ResourceTable.Id_md_stackButtonNegative);

        // Don't allow the submit button to not be shown for input dialogs
        if (builder.inputCallback != null && builder.positiveText == null) {
            builder.positiveText = ResUtil.getString(builder.getContext(), ResourceTable.String_ok);
        }

        // Set up the initial visibility of action buttons based on whether or not text was set
        dialog.positiveButton.setVisibility(builder.positiveText != null ? Component.VISIBLE : Component.HIDE);
        dialog.neutralButton.setVisibility(builder.neutralText != null ? Component.VISIBLE : Component.HIDE);
        dialog.negativeButton.setVisibility(builder.negativeText != null ? Component.VISIBLE : Component.HIDE);

        // Set up the focus of action buttons
        dialog.positiveButton.setFocusable(Component.FOCUS_ENABLE);
        dialog.neutralButton.setFocusable(Component.FOCUS_ENABLE);
        dialog.negativeButton.setFocusable(Component.FOCUS_ENABLE);
        if (builder.positiveFocus) {
            dialog.positiveButton.requestFocus();
        }
        if (builder.neutralFocus) {
            dialog.neutralButton.requestFocus();
        }
        if (builder.negativeFocus) {
            dialog.negativeButton.requestFocus();
        }

        // Setup icon
        if (builder.icon != null) {
            dialog.icon.setVisibility(Component.VISIBLE);
            dialog.icon.setImageElement(builder.icon);
        } else {
            dialog.icon.setVisibility(Component.HIDE);
        }

        // Setup icon size limiting
        int maxIconSize = builder.maxIconSize;
        if (maxIconSize == -1) {
            maxIconSize = ResUtil.getIntDimen(builder.getContext(), ResourceTable.Float_md_icon_max_size);
        }
        if (builder.limitIconToDefaultSize || ResUtil.getBoolean(builder.getContext(), ResourceTable.Boolean_md_icon_limit_icon_to_default_size)) {
            maxIconSize = ResUtil.getIntDimen(builder.getContext(), ResourceTable.Float_md_icon_max_size);
        }
        if (maxIconSize > -1) {
            dialog.icon.setScaleMode(Image.ScaleMode.CENTER);
            dialog.icon.setHeight(maxIconSize);
            dialog.icon.setWidth(maxIconSize);
            dialog.icon.postLayout();
        }

        // Setup divider color in case content scrolls
        if (!builder.dividerColorSet) {
            builder.dividerColor = ResUtil.getColor(builder.getContext(), ResourceTable.Color_md_divider);
        }
        Paint paint = new Paint();
        paint.setColor(new Color(Color.GRAY.getValue()));
        dialog.view.invalidate();

        // Setup title and title frame
        if (dialog.title != null) {
            dialog.setTypeface(dialog.title, builder.mediumFont);
            dialog.title.setTextColor(new Color(builder.titleColor));
            dialog.title.setTextAlignment(builder.titleGravity.getTextAlignment());

            if (builder.title == null) {
                dialog.titleFrame.setVisibility(Component.HIDE);
            } else {
                dialog.title.setText(builder.title.toString());
                dialog.titleFrame.setVisibility(Component.VISIBLE);
            }
        }

        // Setup content
        if (dialog.content != null) {
            dialog.setTypeface(dialog.content, builder.regularFont);
            dialog.content.setLineSpacing(0f, builder.contentLineSpacingMultiplier);
            dialog.content.setTextColor(new Color(builder.contentColor));
            dialog.content.setForegroundGravity(builder.contentGravity.getGravityInt());
            dialog.content.setTextAlignment(builder.contentGravity.getTextAlignment());

            if (builder.content != null) {
                dialog.content.setText(builder.content.toString());
                dialog.content.setVisibility(Component.VISIBLE);
                if (builder.content.length() > Const.LONG_CONTENT_LENGTH) {
                    if (orientation == Configuration.DIRECTION_VERTICAL) {
                        UiUtil.getComponent(dialog.view, ResourceTable.Id_md_contentScrollView)
                                .setLayoutConfig(new ComponentContainer.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT, Const.LONG_CONTENT_HEIGHT));
                    } else {
                        UiUtil.getComponent(dialog.view, ResourceTable.Id_md_contentScrollView)
                                .setLayoutConfig(new ComponentContainer.LayoutConfig(ComponentContainer.LayoutConfig.MATCH_PARENT, Const.LONG_CONTENT_HEIGHT_HOROZONTAL));
                    }

                }
            } else {
                dialog.content.setVisibility(Component.HIDE);
            }
        }

        // Setup prompt checkbox
        if (dialog.checkBoxPrompt != null) {
            dialog.checkBoxPrompt.setText(builder.checkBoxPrompt.toString());
            dialog.checkBoxPrompt.setChecked(builder.checkBoxPromptInitiallyChecked);
            dialog.checkBoxPrompt.setCheckedStateChangedListener(builder.checkBoxPromptListener);
            dialog.setTypeface(dialog.checkBoxPrompt, builder.regularFont);
            dialog.checkBoxPrompt.setTextColor(new Color(builder.contentColor));
            if (builder.checkBoxPromptInitiallyChecked) {
                setAbsButtonBackgroundElement(dialog.checkBoxPrompt, ResourceTable.Media_abc_btn_check_to_on_mtrl_015, ResourceTable.Color_colorAccent, builder.getContext());
            } else {
                setAbsButtonBackgroundElement(dialog.checkBoxPrompt, ResourceTable.Media_abc_btn_check_to_on_mtrl_000, ResourceTable.Color_colorAccent, builder.getContext());
            }
        }
        dialog.view.setButtonGravity(builder.buttonsGravity);
        dialog.view.setButtonStackedGravity(builder.btnStackedGravity);
        dialog.view.setStackingBehavior(builder.stackingBehavior);

        // This code will change the button layout in case of stacked test case
        if (builder.stackingBehavior == StackingBehavior.NEVER) {
            dialog.buttonLayout.setVisibility(Component.HIDE);
            dialog.stackButtonLayout.setVisibility(Component.HIDE);
        } else {
            if (builder.stackingBehavior == StackingBehavior.ALWAYS ||
                    builder.stackingBehavior == StackingBehavior.ADAPTIVE) {
                dialog.buttonLayout.setVisibility(Component.HIDE);
                dialog.stackButtonLayout.setVisibility(Component.VISIBLE);
                if (null != dialog.builder.positiveText) {
                    prepareButtonForUI(dialog, dialog.builder.positiveText, dialog.stackPositiveButton, builder.positiveColor, builder.btnStackedGravity, GravityEnum.START.getTextAlignment(), DialogAction.POSITIVE, dialog.stackButtonLayout);
                }
                if (null != dialog.builder.negativeText) {
                    prepareButtonForUI(dialog, dialog.builder.negativeText, dialog.stackNegativeButton, builder.negativeColor, builder.btnStackedGravity, GravityEnum.END.getTextAlignment(), DialogAction.NEGATIVE, dialog.stackButtonLayout);
                }
            } else {
                dialog.buttonLayout.setVisibility(Component.VISIBLE);
                if (null != dialog.stackButtonLayout) {
                    dialog.stackButtonLayout.setVisibility(Component.HIDE);
                }
            }
            if (null != dialog.builder.positiveText) {
                prepareButtonForUI(dialog, dialog.builder.positiveText, dialog.positiveButton, builder.positiveColor, null, GravityEnum.START.getTextAlignment(), DialogAction.POSITIVE, null);
            }
            if (null != dialog.builder.negativeText) {
                prepareButtonForUI(dialog, dialog.builder.negativeText, dialog.negativeButton, builder.negativeColor, null, GravityEnum.END.getTextAlignment(), DialogAction.NEGATIVE, null);
            }
            if (null != builder.neutralText) {
                prepareButtonForUI(dialog, dialog.builder.neutralText, dialog.neutralButton, builder.neutralColor, null, GravityEnum.CENTER.getTextAlignment(), DialogAction.NEUTRAL, null);
            }
        }

        // Setup list dialog stuff
        if (builder.listCallbackMultiChoice != null) {
            dialog.selectedIndicesList = new ArrayList<>();
        }
        if (dialog.listContainer != null) {
            if (builder.baseItemProvider == null) {
                // Determine list type
                if (builder.listCallbackSingleChoice != null) {
                    dialog.listType = MaterialDialog.ListType.SINGLE;
                } else if (builder.listCallbackMultiChoice != null) {
                    dialog.listType = MaterialDialog.ListType.MULTI;
                    if (builder.selectedIndices != null) {
                        dialog.selectedIndicesList = new ArrayList<>(Arrays.asList(builder.selectedIndices));
                        builder.selectedIndices = null;
                    }
                } else {
                    dialog.listType = MaterialDialog.ListType.REGULAR;
                }
                builder.baseItemProvider =
                        new DefaultRvAdapter(dialog, MaterialDialog.ListType.getLayoutForType(dialog.listType), builder.getContext());
            } else if (builder.baseItemProvider instanceof MDAdapter) {
                // Notify simple list adapter of the dialog it belongs to
                ((MDAdapter) builder.baseItemProvider).setDialog(dialog);
            }
        }

        // Setup progress dialog stuff if needed
        setupProgressDialog(dialog);

        // Setup input dialog stuff if needed
        setupInputDialog(dialog);


        // Setup custom views
        if (builder.customView != null) {
            ((MDRootLayout) UiUtil.getComponent(dialog.view, ResourceTable.Id_md_root)).noTitleNoPadding();
            StackLayout frame = UiUtil.getComponent(dialog.view, ResourceTable.Id_md_customViewFrame);
            dialog.customViewFrame = frame;
            Component innerView = builder.customView;
            if (innerView.getComponentParent() != null) {
                innerView.getComponentParent().removeComponent(innerView);
            }
            if (builder.wrapCustomViewInScroll) {
             /* Apply the frame padding to the content, this allows the ScrollView to draw it's
             over scroll glow without clipping */
                final int framePadding = ResUtil.getIntDimen(builder.getContext(), ResourceTable.Float_md_dialog_frame_margin);
                final ScrollView sv = new ScrollView(builder.getContext());
                int paddingTop = ResUtil.getIntDimen(builder.getContext(), ResourceTable.Float_md_content_padding_top);
                int paddingBottom = ResUtil.getIntDimen(builder.getContext(), ResourceTable.Float_md_content_padding_bottom);
                if (innerView instanceof TextField) {
                    // Setting padding to an EditText causes visual errors, set it to the parent instead
                    sv.setPadding(framePadding, paddingTop, framePadding, paddingBottom);
                } else {
                    // Setting padding to scroll view pushes the scroll bars out, don't do it if not necessary (like above)
                    sv.setPadding(0, paddingTop, 0, paddingBottom);
                    innerView.setPadding(framePadding, 0, framePadding, 0);
                }
                sv.addComponent(
                        innerView,
                        new ScrollView.LayoutConfig(
                                ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_CONTENT));
                innerView = sv;
            }
            frame.addComponent(
                    innerView,
                    new ComponentContainer.LayoutConfig(
                            ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_CONTENT));
        }

        // Setup user listeners
        if (builder.showListener != null) {
            dialog.setOnShowListener(builder.showListener);
        }
        if (builder.cancelListener != null) {
            dialog.setOnCancelListener(builder.cancelListener);
        }
        if (builder.dismissListener != null) {
            dialog.setOnDismissListener(builder.dismissListener);
        }

        // Setup internal show listener
        dialog.setOnShowListenerInternal();

        // Other internal initialization
        dialog.invalidateList();
        dialog.setViewInternal(dialog.view);
        dialog.checkIfListInitScroll();

        // Min height and max width calculations
        Optional<Display> optionalDisplay = DisplayManager.getInstance().getDefaultDisplay(builder.getContext());
        Display display = optionalDisplay.get();
        Point size = new Point();
        display.getSize(size);
        final int windowWidth = (int) size.position[0];
        final int windowHeight = (int) size.position[1];

        final int windowVerticalPadding = ResUtil.getIntDimen(builder.getContext(),
                ResourceTable.Float_md_dialog_vertical_margin);
        final int windowHorizontalPadding = ResUtil.getIntDimen(builder.getContext(),
                ResourceTable.Float_md_dialog_horizontal_margin);
        final int maxWidth = ResUtil.getIntDimen(builder.getContext(), ResourceTable.Float_md_dialog_max_width);
        final int calculatedWidth = windowWidth - (windowHorizontalPadding * 2);
        int calculatedHeight = windowHeight - windowVerticalPadding * 2;
        dialog.view.setMaxHeight(calculatedHeight);
        WindowManager.LayoutConfig lp = new WindowManager.LayoutConfig();
        lp.width = Math.min(maxWidth, calculatedWidth);
        dialog.getWindow().setLayoutConfig(lp);
    }

    private static void prepareButtonForUI(MaterialDialog dialog, CharSequence buttonText, MDButton button, int color, GravityEnum btnStackedGravity, int textAlignment, DialogAction action, DirectionalLayout stackButtonLayout) {
        // Setup action buttons
        boolean textAllCaps = ResUtil.getBoolean(dialog.builder.getContext(), ResourceTable.Boolean_textAllCaps);
        // String color = String.format("#%06X", (0xFFFFFF & 16842806));
        button.setTextColor(new Color(color));
        dialog.setTypeface(button, dialog.builder.mediumFont);
        String text = buttonText.toString() != null ? buttonText.toString() : "";
        if (textAllCaps && !text.equals("")) {
            text = text.toUpperCase();
        }
        button.setText(text);
        if (null != btnStackedGravity && null != stackButtonLayout) {
            switch (btnStackedGravity) {
                case START:
                    stackButtonLayout.setAlignment(LayoutAlignment.START);
                    stackButtonLayout.setMarginLeft(40);
                    break;
                case CENTER:
                    stackButtonLayout.setAlignment(LayoutAlignment.CENTER);
                    stackButtonLayout.setPaddingTop(5);
                    stackButtonLayout.setPaddingBottom(5);
                    break;
                case END:
                    stackButtonLayout.setAlignment(LayoutAlignment.END);
                    stackButtonLayout.setMarginRight(40);
                    break;
                default:
                    throw new IllegalStateException("Invalid gravity constant");
            }
        }
        button.setTextAlignment(textAlignment);
        button.setStackedSelector(dialog.getButtonSelector(action, true));
        button.setDefaultSelector(dialog.getButtonSelector(action, false));
        button.setTag(action);
        button.setClickedListener(dialog);
    }

    private static void setupProgressDialog(final MaterialDialog dialog) {
        final MaterialDialog.Builder builder = dialog.builder;
        if (builder.indeterminateProgress || builder.progress > -2) {
            dialog.progressBar = (ProgressBar) dialog.view.findComponentById(ResourceTable.Id_progress);
            if (dialog.progressBar == null) {
                return;
            }
            dialog.progressBar.setProgressColor(new Color(dialog.builder.widgetColor));

            if (!builder.indeterminateProgress || builder.indeterminateIsHorizontalProgress) {
                dialog.progressBar.setIndeterminate(
                        builder.indeterminateProgress && builder.indeterminateIsHorizontalProgress);
                dialog.progressBar.setProgressValue(0);
                dialog.progressBar.setMaxValue(builder.progressMax);
                dialog.progressLabel = (Text) dialog.view.findComponentById(ResourceTable.Id_md_label);
                if (dialog.progressLabel != null) {
                    dialog.progressLabel.setTextColor(new Color(builder.contentColor));
                    dialog.setTypeface(dialog.progressLabel, builder.mediumFont);
                    dialog.progressLabel.setText(builder.progressPercentFormat.format(0));
                }
                dialog.progressMinMax = (Text) dialog.view.findComponentById(ResourceTable.Id_md_minMax);
                if (dialog.progressMinMax != null) {
                    dialog.progressMinMax.setTextColor(new Color(builder.contentColor));
                    dialog.setTypeface(dialog.progressMinMax, builder.regularFont);

                    if (builder.showMinMax) {
                        dialog.progressMinMax.setVisibility(Component.VISIBLE);
                        dialog.progressMinMax.setText(
                                String.format(builder.progressNumberFormat, 0, builder.progressMax));
                        ComponentContainer.LayoutConfig lp = dialog.progressBar.getLayoutConfig();
                        lp.setMargins(0, lp.getMarginTop(), 0, lp.getMarginBottom());
                    } else {
                        dialog.progressMinMax.setVisibility(Component.HIDE);
                    }
                } else {
                    builder.showMinMax = false;
                }
            }
        }
    }

    private static void setupInputDialog(final MaterialDialog dialog) {
        final MaterialDialog.Builder builder = dialog.builder;
        dialog.input = (TextField) dialog.view.findComponentById(ResourceTable.Id_input);
        if (dialog.input == null) {
            return;
        }
        dialog.setTypeface(dialog.input, builder.regularFont);
        if (builder.inputPrefill != null) {
            dialog.input.setText(builder.inputPrefill.toString());
        }
        dialog.setInternalInputCallback();
        dialog.input.setHint(builder.inputHint.toString());
        dialog.input.setMaxTextLines(1);
        dialog.input.setTextColor(new Color(builder.contentColor));

        if (builder.inputType != -1) {
            dialog.input.setTextInputType(builder.inputType);
        }
        ShapeElement shapeElement = new ShapeElement();
        shapeElement.setShape(ShapeElement.LINE);
        shapeElement.setStroke(5, RgbColor.fromArgbInt(dialog.builder.widgetColor));
        dialog.input.setBasement(shapeElement);

        dialog.inputMinMax = (Text) dialog.view.findComponentById(ResourceTable.Id_md_minMax);
        if (builder.inputMinLength > 0 || builder.inputMaxLength > -1) {
            dialog.invalidateInputMinMaxIndicator(
                    dialog.input.getText().length(), !builder.inputAllowEmpty);
        } else {
            dialog.inputMinMax.setVisibility(Component.HIDE);
            dialog.inputMinMax = null;
        }
    }

    /**
     * This method is used to set background element & background color of radiobutton & checkbox
     *
     * @param context
     * @param absButton Radiobutton/Checkbox
     * @param drawable  Resource drawable for checked/uncheked
     * @param color     Color as per checked/unchecked
     */
    private static void setAbsButtonBackgroundElement(AbsButton absButton, int drawable, int color, Context context) {
        absButton.setButtonElement(ResUtil.getPixelMapDrawable(context, drawable));
    }
}
